{% extends "base.html" %}

{% block title %}图书管理 - 墨韵图书共享平台{% endblock %}

{% block content %}
<div class="admin-panel">
    <div class="row mb-4">
        <div class="col-md-12">
            <h2 class="ink-decoration mb-4">图书管理</h2>
            <p class="text-muted">在这里您可以管理所有图书，包括审核新图书、编辑图书信息等。</p>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-3">
            <div class="card ink-card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">管理菜单</h5>
                </div>
                <div class="list-group list-group-flush">
                    <a href="{{ url_for('admin_panel') }}" class="list-group-item list-group-item-action">
                        <i class="fas fa-tachometer-alt me-2"></i> 仪表盘
                    </a>
                    <a href="{{ url_for('admin_books') }}" class="list-group-item list-group-item-action active">
                        <i class="fas fa-book me-2"></i> 图书管理
                    </a>
                    <a href="{{ url_for('admin_users') }}" class="list-group-item list-group-item-action">
                        <i class="fas fa-users me-2"></i> 用户管理
                    </a>
                    <a href="{{ url_for('admin_categories') }}" class="list-group-item list-group-item-action">
                        <i class="fas fa-tags me-2"></i> 分类管理
                    </a>
                    <a href="{{ url_for('admin_statistics') }}" class="list-group-item list-group-item-action">
                        <i class="fas fa-chart-bar me-2"></i> 使用统计
                    </a>
                </div>
            </div>
            
            <div class="card ink-card">
                <div class="card-header">
                    <h5 class="mb-0">筛选</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">状态</label>
                        <div class="d-grid gap-2">
                            <a href="{{ url_for('admin_books', status='all') }}" class="btn {% if status == 'all' %}btn-primary{% else %}btn-outline-primary{% endif %} btn-sm">
                                全部
                            </a>
                            <a href="{{ url_for('admin_books', status='pending') }}" class="btn {% if status == 'pending' %}btn-primary{% else %}btn-outline-primary{% endif %} btn-sm">
                                待审核
                            </a>
                            <a href="{{ url_for('admin_books', status='approved') }}" class="btn {% if status == 'approved' %}btn-primary{% else %}btn-outline-primary{% endif %} btn-sm">
                                已通过
                            </a>
                            <a href="{{ url_for('admin_books', status='rejected') }}" class="btn {% if status == 'rejected' %}btn-primary{% else %}btn-outline-primary{% endif %} btn-sm">
                                已拒绝
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-9">
            <div class="card ink-card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">图书列表</h5>
                    <span class="badge bg-info">{{ books.total }} 本图书</span>
                </div>
                <div class="card-body">
                    {% if books.items %}
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>封面</th>
                                        <th>书名</th>
                                        <th>作者</th>
                                        <th>上传者</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for book in books.items %}
                                        <tr>
                                            <td>{{ book.id }}</td>
                                            <td style="width: 60px;">
                                                {% if book.cover_path %}
                                                    <img src="{{ url_for('static', filename='covers/' + book.cover_path) }}" 
                                                         class="img-thumbnail" style="width: 50px; height: 70px; object-fit: cover;">
                                                {% else %}
                                                    <div class="cover-placeholder" style="width: 50px; height: 70px; font-size: 0.7rem;">
                                                        {{ book.title[:10] }}
                                                    </div>
                                                {% endif %}
                                            </td>
                                            <td>
                                                <a href="{{ url_for('view_book', book_id=book.id) }}" target="_blank">
                                                    {{ book.title }}
                                                </a>
                                            </td>
                                            <td>{{ book.author }}</td>
                                            <td>
                                                {% if book.uploader %}
                                                    {{ book.uploader.username }}
                                                {% else %}
                                                    未知
                                                {% endif %}
                                            </td>
                                            <td>
                                                {% if book.status == 'pending' %}
                                                    <span class="status-badge status-pending">待审核</span>
                                                {% elif book.status == 'approved' %}
                                                    <span class="status-badge status-approved">已通过</span>
                                                {% elif book.status == 'rejected' %}
                                                    <span class="status-badge status-rejected">已拒绝</span>
                                                {% endif %}
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <a href="{{ url_for('view_book', book_id=book.id) }}" class="btn btn-outline-primary">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    {% if book.status == 'pending' %}
                                                        <button type="button" class="btn btn-outline-success approve-direct-btn" data-book-id="{{ book.id }}" data-book-title="{{ book.title }}">
                                                            <i class="fas fa-check"></i>
                                                        </button>
                                                        <button type="button" class="btn btn-outline-danger reject-direct-btn" data-book-id="{{ book.id }}" data-book-title="{{ book.title }}">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    {% endif %}
                                                </div>
                                            </td>
                                        </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 分页 -->
                        {% if books.pages > 1 %}
                            <nav aria-label="图书分页">
                                <ul class="pagination justify-content-center">
                                    {% if books.has_prev %}
                                        <li class="page-item">
                                            <a class="page-link" href="{{ url_for('admin_books', page=books.prev_num, status=status) }}">上一页</a>
                                        </li>
                                    {% else %}
                                        <li class="page-item disabled">
                                            <a class="page-link" href="#" tabindex="-1" aria-disabled="true">上一页</a>
                                        </li>
                                    {% endif %}
                                    
                                    {% for page_num in books.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
                                        {% if page_num %}
                                            {% if page_num == books.page %}
                                                <li class="page-item active">
                                                    <a class="page-link" href="#">{{ page_num }}</a>
                                                </li>
                                            {% else %}
                                                <li class="page-item">
                                                    <a class="page-link" href="{{ url_for('admin_books', page=page_num, status=status) }}">{{ page_num }}</a>
                                                </li>
                                            {% endif %}
                                        {% else %}
                                            <li class="page-item disabled">
                                                <a class="page-link" href="#">...</a>
                                            </li>
                                        {% endif %}
                                    {% endfor %}
                                    
                                    {% if books.has_next %}
                                        <li class="page-item">
                                            <a class="page-link" href="{{ url_for('admin_books', page=books.next_num, status=status) }}">下一页</a>
                                        </li>
                                    {% else %}
                                        <li class="page-item disabled">
                                            <a class="page-link" href="#" tabindex="-1" aria-disabled="true">下一页</a>
                                        </li>
                                    {% endif %}
                                </ul>
                            </nav>
                        {% endif %}
                    {% else %}
                        <p class="text-center text-muted">暂无图书</p>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<!-- 服务器端渲染好的数据，以data属性传递给JavaScript -->
<div id="jinja-data" 
     data-approve-url="{{ url_for('approve_book', book_id=0) }}"
     data-reject-url="{{ url_for('reject_book', book_id=0) }}"
     {% if csrf_token %}
     data-csrf-token="{{ csrf_token }}"
     {% endif %}
     style="display:none;"></div>

<!-- 纯JavaScript代码，不包含任何Jinja2语法 -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 从DOM中获取数据属性
        var dataElement = document.getElementById('jinja-data');
        var approveBookUrl = dataElement.getAttribute('data-approve-url');
        var rejectBookUrl = dataElement.getAttribute('data-reject-url');
        var csrfToken = dataElement.getAttribute('data-csrf-token');
        
        // 设置jQuery的AJAX全局设置，添加CSRF保护
        if (csrfToken) {
            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrfToken);
                    }
                }
            });
        }
        
        // 直接批准图书按钮
        document.querySelectorAll('.approve-direct-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                const bookId = this.getAttribute('data-book-id');
                const bookTitle = this.getAttribute('data-book-title');
                
                if (confirm(`您确定要批准《${bookTitle}》这本图书吗？批准后，该图书将对所有用户可见。`)) {
                    // 禁用按钮防止重复提交
                    this.disabled = true;
                    this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>';
                    
                    // 使用原生JavaScript发送POST请求
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', approveBookUrl.replace('0', bookId), true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    if (csrfToken) {
                        xhr.setRequestHeader('X-CSRFToken', csrfToken);
                    }
                    
                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            window.location.reload();
                        } else {
                            alert('批准失败，请重试');
                            btn.disabled = false;
                            btn.innerHTML = '<i class="fas fa-check"></i>';
                        }
                    };
                    
                    xhr.onerror = function() {
                        alert('批准失败，请重试');
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-check"></i>';
                    };
                    
                    xhr.send();
                }
            });
        });
        
        // 直接拒绝图书按钮
        document.querySelectorAll('.reject-direct-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                const bookId = this.getAttribute('data-book-id');
                const bookTitle = this.getAttribute('data-book-title');
                
                const reason = prompt(`您确定要拒绝《${bookTitle}》这本图书吗？\n\n请输入拒绝原因：`);
                if (reason !== null) {
                    if (reason.trim() === '') {
                        alert('请输入拒绝原因');
                        return;
                    }
                    
                    // 禁用按钮防止重复提交
                    this.disabled = true;
                    this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>';
                    
                    // 使用原生JavaScript发送POST请求
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', rejectBookUrl.replace('0', bookId), true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    if (csrfToken) {
                        xhr.setRequestHeader('X-CSRFToken', csrfToken);
                    }
                    
                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            window.location.reload();
                        } else {
                            alert('拒绝失败，请重试');
                            btn.disabled = false;
                            btn.innerHTML = '<i class="fas fa-times"></i>';
                        }
                    };
                    
                    xhr.onerror = function() {
                        alert('拒绝失败，请重试');
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-times"></i>';
                    };
                    
                    xhr.send('reason=' + encodeURIComponent(reason));
                }
            });
        });
    });
</script>
{% endblock %} 